const wx_server_sdk = require('wx-server-sdk');

wx_server_sdk.init({
    env: 'direshui-6gl2m2r1275bd635'
});
const db = wx_server_sdk.database();
const dbCommand = db.command;


async function funcMain(e) {
    var nowTime = getBeijingTime();
    console.log('当前时间', nowTime);


    //1600590926

    //目标:每分钟,生成开采井瞬时和正向,回灌井瞬时和正向

    var dev_nowFlow = 350 + 20 * Math.random();
    dev_nowFlow = Math.floor(dev_nowFlow * 100) / 100;

    var tsBase = nowTime.ts / 10000 - 160000000 + 4;
    var dev_accu = Math.floor((tsBase + 2 * Math.random()) * 100) / 100;
    var bak_accu = Math.floor((tsBase + 2 * Math.random()) * 100) / 100;

    console.log('模拟基数', tsBase, '模拟的开采量',
        dev_accu, '模拟的回灌量', bak_accu, '未回灌量', dev_accu - bak_accu);

    var bak_nowFlow = dev_nowFlow - 20 * Math.random();
    bak_nowFlow = Math.floor(bak_nowFlow * 100) / 100;



    var saveToDb = await db.collection('nowData').add({
        data: {
            nowFlow: dev_nowFlow,
            rightAccuFlow: dev_accu,
            time: nowTime.time,
            ts: Math.floor(nowTime.ts / 1000),
            wellName: '刘庄开采井',
            wellType: '开采井',
        }
    })

    // console.log('保存开采井数据情况', saveToDb);

    saveToDb = await db.collection('nowData').add({
        data: {
            nowFlow: bak_nowFlow,
            rightAccuFlow: bak_accu,
            time: nowTime.time,
            ts: Math.floor(nowTime.ts / 1000),
            wellName: '刘庄回灌井',
            wellType: '回灌井',
        }
    })

    // console.log('保存回灌井数据情况', saveToDb);

    return;
}


function getNowTimestamp() {
    return new Date().getTime();
}

function getBeijingTime(localTs) {
    var time_ts = localTs;
    if (typeof(localTs) != 'number' || localTs == 0) {
        time_ts = getNowTimestamp();
    }

    var time = tsToDateStr(time_ts);

    return {
        ts: time_ts,
        time,
    };
}

function tsToDateStr(ts_para) {
    //2020-06-14 20:49:59
    //未在此弥补时差
    var time_ts = new Date(ts_para + 8 * 3600000);

    // console.log('用于制作中文的ts', time_ts.getTime());

    var time_str = time_ts.getFullYear() + '-';

    if ((time_ts.getMonth() + 1) < 10) {
        time_str += '0';
    }
    time_str += '' + (time_ts.getMonth() + 1) + '-';


    if (time_ts.getDate() < 10) {
        time_str += '0';
    }
    time_str += '' + time_ts.getDate() + ' ';


    if (time_ts.getHours() < 10) {
        time_str += '0';
    }
    time_str += '' + time_ts.getHours() + ':';

    if (time_ts.getMinutes() < 10) {
        time_str += '0';
    }
    time_str += '' + time_ts.getMinutes() + ':';

    if (time_ts.getSeconds() < 10) {
        time_str += '0';
    }
    time_str += '' + time_ts.getSeconds(); // + ':' + time_ts.getMilliseconds();

    return time_str;
}


exports.main = funcMain